<?php
declare (strict_types = 1);

namespace app\controller\frontend;

use app\BaseController as AppBaseController;
use app\model\Theme;
use app\model\Visit;
use app\model\VisitLog;
use app\model\Website;
use think\facade\View;

class BaseController extends AppBaseController
{
    protected $domain;
    protected $siteId;
    protected $sellerId;
    protected $theme;
    protected $lang;
    protected $viewBase;


    /**
     * @throws \app\exception\ModelException
     * @throws \Exception
     */
    public function initialize()
    {
        $this->setCommonParam();
        $this->getActiveTheme();
        $this->setVisitedData();
        parent::initialize();
    }

    /**
     * @throws \app\exception\ModelException
     */
    public function setCommonParam()
    {
        $domain = $this->request->host();
        $Website = new Website();
        $website = $Website->getWebsiteByDomain($domain,'id,domain,seller_id')['data'];
        $this->domain = $domain;
        $this->siteId = $website['id'];
        $this->sellerId = $website['seller_id'];
        $this->lang = $this->setLang();
        $this->viewBase = config('view.view_dir_name');
        define('INDEX_SITE_ID',$this->siteId);
        define('INDEX_SELLER_ID',$this->sellerId);
        define('INDEX_LANG',$this->lang);
    }

    /**
     * @throws \app\exception\ModelException
     */
    public function getActiveTheme()
    {
        $Theme = new Theme();
        $theme = $Theme->getActiveTheme(['seller_id'=>$this->sellerId,'website_id'=>$this->siteId,'lang'=>$this->lang,'is_active'=>1])['data']->toArray();
        $this->theme = $theme['name'];
    }

    public function setLang(): string
    {
        $baseUrl = trim($this->request->baseUrl(),'/');
        $firstPath = explode('/',$baseUrl)[0];
        $langArr = config('system.lang');
        if(empty($firstPath) || !in_array($firstPath,$langArr)){
            $firstPath = 'zh';
        }
        return $firstPath;
    }

    protected function assign($name,$value): \think\View
    {
        return View::assign($name, $value);
    }

    /**
     * 加载模板输出
     * @access protected
     * @param string $template 模板文件名
     * @param array  $vars     模板输出变量
     * @return mixed
     */
    protected function fetch($template = '', $vars = [])
    {
        $template = $this->parseTemplate($template);

        $this->_initializeView($this->siteId,$this->lang,$this->theme);

        return View::fetch($template, $vars);
    }

    /**
     * 定位模板
     * @param $template
     * @return string
     */
    private function parseTemplate($template): string
    {

        $path = CMS_ROOT . $this->viewBase . DIRECTORY_SEPARATOR . $this->siteId.DIRECTORY_SEPARATOR .$this->lang.DIRECTORY_SEPARATOR.$this->theme;

        return $path . DIRECTORY_SEPARATOR . ltrim($template,'/').'.'.config('view.view_suffix');
    }

    /**
     * 常量替换
     * @param $siteId
     * @param $lang
     * @param $themeName
     */
    protected function _initializeView($siteId,$lang,$themeName)
    {
        //使cdn设置生效
        $viewReplaceStr = [
            '__TMPL__'     => "/themes/website/{$siteId}/{$lang}/{$themeName}",
            '__STATIC__'   => "/themes/website/{$siteId}/{$lang}/{$themeName}/static",
        ];
        View::engine()->config([
            'view_path' => CMS_ROOT . $this->viewBase . DIRECTORY_SEPARATOR . $this->siteId.DIRECTORY_SEPARATOR .$this->lang.DIRECTORY_SEPARATOR.$this->theme .DIRECTORY_SEPARATOR,
            'tpl_replace_string' => $viewReplaceStr,
            'display_cache' => false,
            'tpl_cache' => false,
        ]);
    }

    /**
     * @throws \Exception
     */
    private function setVisitedData()
    {
        $VisitLog = new VisitLog();
        $ip = request()->ip();
        $agent = request()->header()['user-agent'];
        $address = getLocationByIp($ip,2);
        if(empty($address['province'])){
            $area = "内网ip";
        }else{
            $area = $address['province']."-".$address['city'];
        }
        $url = $this->request->domain().$this->request->url();
        $device = getDeviceInfo($agent);
        $param = [
            'seller_id' => $this->sellerId,
            'website_id' => $this->siteId,
            'domain' => $this->domain,
            'url' => $url,
            'ip' => $ip,
            'visited_area' => $area,
            'visited_device' => $device['deviceOs'] .'/'.$device['deviceVersion'],
            'visited_time'  => date('Y-m-d',time())
        ];

        $VisitLog -> addCustomData($param);
    }
}
